package com.southminority.ethnic.enums;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis键枚举类
 */
public enum RedisKeyEnum {



    // 用户相关
    USER_TOKEN("user:token:", null, null, "用户token"),
    USER_INFO("user:info:", 24L , TimeUnit.HOURS, "用户信息"),
    USER_ONLINE("user:online:", 30L, TimeUnit.MINUTES, "用户在线状态"),

    // 验证码相关
    CAPTCHA_REGISTER("captcha:register:", 5L, TimeUnit.MINUTES, "注册验证码"),
    CAPTCHA_FORGET("captcha:forget:", 5L, TimeUnit.MINUTES, "忘记密码验证码"),
    CAPTCHA_LIMIT("captcha:limit:", 1L, TimeUnit.MINUTES, "验证码发送限制")

    ;



    private final String keyPrefix;
    private  Long expireTime;
    private  TimeUnit timeUnit;
    private  final String description;

    /**
     * 配置类，专门用于设置USER_TOKEN的过期时间
     */
    @Component
    public static class RedisKeyConfig {

        @Value("${self.redis.token-life-cycle}")
        private Long tokenLifeCycle;
        @Value("${self.redis.token-description-type}")
        private String tokenDescriptionType;

        @PostConstruct
        public void init() {
            // 只为USER_TOKEN设置配置值
            USER_TOKEN.expireTime = tokenLifeCycle;
            USER_TOKEN.timeUnit = TimeUnit.valueOf(tokenDescriptionType);
        }
    }



    RedisKeyEnum(String keyPrefix, Long expireTime, TimeUnit timeUnit, String description) {
        this.keyPrefix = keyPrefix;
        this.expireTime = expireTime;
        this.timeUnit = timeUnit;
        this.description = description;
    }

    /**
     * 生成完整的Redis key
     */
    public String getKey(Object... params) {
        if (params == null || params.length == 0) {
            return keyPrefix;
        }
        return keyPrefix + String.join(":", convertParams(params));
    }

    /**
     * 获取过期时间（毫秒）
     */
    public long getExpireMillis() {
        if (expireTime == -1) {
            return -1; // 永不过期
        }
        return timeUnit.toMillis(expireTime);
    }

    /**
     * 获取过期时间（秒）
     */
    public long getExpireSeconds() {
        if (expireTime == -1) {
            return -1; // 永不过期
        }
        return timeUnit.toSeconds(expireTime);
    }

    /**
     * 是否永不过期
     */
    public boolean isPersistent() {
        return expireTime == -1;
    }

    private String[] convertParams(Object... params) {
        String[] result = new String[params.length];
        for (int i = 0; i < params.length; i++) {
            result[i] = String.valueOf(params[i]);
        }
        return result;
    }

    // Getter方法
    public String getKeyPrefix() {
        return keyPrefix;
    }

    public long getExpireTime() {
        return expireTime;
    }

    public TimeUnit getTimeUnit() {
        return timeUnit;
    }

    public String getDescription() {
        return description;
    }
}